package com.xqiapp.xframe.plugin.codes;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xqiapp.xframe.plugin.codes.gen.IGenraterHandler;
import com.xqiapp.xframe.plugin.codes.util.ClassUtil;
import com.xqiapp.xframe.plugin.codes.util.PropsUtil;

import freemarker.template.TemplateException;

/**
 * 
 * 用于测试类生成的方法
 * 
 * @author mike
 * @date 2016年7月13日
 * @version 0.0.1
 */
public class ClassGenrater {
	private static final Logger LOG = LoggerFactory.getLogger(ClassGenrater.class);
	
	public static final String SCAN_PKG = PropsUtil.getString("code.load_pkg");
	public static final String OUT_PKG = PropsUtil.getString("code.out_pkg");
	public static final String TEMP_FILE_DIR = PropsUtil.getString("code.temp_FileDir");
	public static final String TEMP_FILE_NAME = PropsUtil.getString("code.temp_FileName");
	public static final String TEMP_HANDLER = PropsUtil.getString("code.temp_handler");
	
	public static final String CONFIG_FILE_PATH = PropsUtil.getString("code.config_filePath");
	
	

	private String outPkg;
	private String tempFileDir;
	private String tempFileName;
	private String scanPkg;
	
	private IGenraterHandler handler;

	/**
	 * 使用配置文件配置
	 */
	public ClassGenrater(){
		this.tempFileDir = TEMP_FILE_DIR;
		this.outPkg = OUT_PKG;
		this.scanPkg = SCAN_PKG;
		this.tempFileName = TEMP_FILE_NAME;
		try {
			handler = (IGenraterHandler) ClassUtil.loadClassInstanceCurrentLoader(TEMP_HANDLER);
		} catch (Exception e) {
			throw new RuntimeException("The handler intsance error,check the settings!");
		}
	}
	
	/**
	 * 使用代码设置路径配置
	 * @param basePkg
	 * @param outPkg
	 * @param tempFileDir
	 * @param type
	 */
	public ClassGenrater(String scanPkg,String outPkg, String tempFileDir,String tempFileName,IGenraterHandler handler) {
		this.scanPkg = scanPkg;
		this.tempFileDir = tempFileDir;
		this.outPkg = outPkg;
		this.tempFileName = tempFileName;
		this.handler = handler;
	}
	
	/**
	 * 调用生成
	 * 
	 * @throws IOException
	 * @throws TemplateException
	 */
	public void gener() throws IOException, TemplateException {
		LOG.info("[Starting Genrater] [config] ---scan:"+scanPkg+" out:"+outPkg +" tempFileDir:"+ tempFileDir +" tempFileName:"+tempFileName);
		handler.handle(scanPkg,outPkg,tempFileDir,tempFileName);
	}

}
